package com.weiaibenpao.demo.chislim.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.base.BaseFragment;
import com.weiaibenpao.demo.chislim.bean.Moment;
import com.weiaibenpao.demo.chislim.bean.MomentEvent;
import com.weiaibenpao.demo.chislim.bean.MomentListBean;
import com.weiaibenpao.demo.chislim.db.preferences.UserPreferences;
import com.weiaibenpao.demo.chislim.presenter.MomentListPresenter;
import com.weiaibenpao.demo.chislim.ui.activity.moment.MessageListActivity;
import com.weiaibenpao.demo.chislim.ui.adapter.MomentListAdapter;
import com.weiaibenpao.demo.chislim.ui.widget.MomentActionDialog;
import com.weiaibenpao.demo.chislim.ui.widget.MomentView;
import com.weiaibenpao.demo.chislim.ui.widget.ReportSelectDialog;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.view.MomentListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;


public class MomentListFragment extends BaseFragment<MomentListView,MomentListPresenter>  implements  MomentListView,SwipeRefreshLayout.OnRefreshListener,BaseQuickAdapter.RequestLoadMoreListener,BaseQuickAdapter.OnItemChildClickListener{
    public static final String LIST_TYPE ="list_type";
    public static final String TYPE_LATEST ="type_latest";
    public static final String TYPE_FOLLOWED ="type_followed";
    public static final String LIKE_SUCCESS = "点赞成功";
    public static final String UNLIKE_SUCCESS = "取消点赞成功";
    private MomentListAdapter mAdapter;
    private String mListType;
    private int mMineId;
    private int mNextPage =1 ;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.rv_list)
    RecyclerView mMomentList;

    public static MomentListFragment newInstance(String listType) {
        Bundle args = new Bundle();
        args.putString(LIST_TYPE, listType);
        MomentListFragment fragment = new MomentListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_moment_list;
    }

    @Override
    protected MomentListPresenter initPresenter() {
        return new MomentListPresenter();
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mMineId = UserPreferences.getInstance().getInt(UserPreferences.USER_ID);
        // onHiddenChanged没回调
        // 当listType为latest 时HeadView：1) 读完消息移除head view  2) 新到推送消息更新head view---后台推送消息暂不做了
//        mUserId = 43;
        if(getArguments() != null) mListType = getArguments().getString(LIST_TYPE);
        initView();
        refresh();
    }

    private void initView() {
        mAdapter = new MomentListAdapter();
        mAdapter.setOnLoadMoreListener(this,mMomentList);
        mAdapter.setOnItemChildClickListener(this);
//        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
//        mAdapter.setPreLoadNumber(3);
        mMomentList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mMomentList.setAdapter(mAdapter);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setRefreshing(true);
    }

    private View mHeadView ;
    private void updateHeadView(String avatarUrl ,int unreadCount){
        if(mHeadView == null){
            mHeadView = getLayoutInflater().inflate(R.layout.layout_unread_msg_notice, (ViewGroup) mMomentList.getParent(), false);
            mHeadView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MessageListActivity.startSelf(getActivity(),MomentListFragment.this);
                }
            });
            mAdapter.addHeaderView(mHeadView);// 也可以setHeaderView
        }
        ImageView msgFromAvatar = mHeadView.findViewById(R.id.iv_header);
        TextView  tvUnreadCount = mHeadView.findViewById(R.id.tv_unread_count);
        String unreadCountStr = String.valueOf(unreadCount);
        if(unreadCount>99) unreadCountStr = getString(R.string.max_msg_display_count);
        tvUnreadCount.setText(getString(R.string.new_message_count, unreadCountStr));
        if(TextUtils.isEmpty(avatarUrl)){
            msgFromAvatar.setVisibility(View.GONE);
        }else {
            msgFromAvatar.setVisibility(View.VISIBLE);
            Glide.with(this).load(avatarUrl).into(msgFromAvatar);
        }
    }

    private void removeHeadView(){
        if(mHeadView != null){
            mAdapter.removeHeaderView(mHeadView);
            mHeadView = null;
        }
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }


    public void refresh() {
        Logger.e("MomentListFrag--refresh");
        mNextPage = 1;
        mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        doRequest();
    }

    private void loadMore() {
        Logger.e("MomentListFrag--loadMore");
        doRequest();
    }

    private void doRequest() {
        if(TYPE_LATEST.equals(mListType)) {
            mPresenter.getLatestMoments(mMineId,mNextPage);
        }else {
            mPresenter.getCaredMoments(mMineId,mNextPage);
        }
    }

    private void setData(boolean isRefresh, List<Moment> data) {
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < Constant.DEFAULT_PAGE_SIZE) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onGetMomentListSuccess(MomentListBean momentListBean) {
        mSwipeRefreshLayout.setRefreshing(false);
        boolean isRefresh = mNextPage == 1;
//        if(isRefresh)  mAdapter.setEnableLoadMore(true);
        if(TYPE_LATEST.equals(mListType) && momentListBean.getCountRealInfo() >0){
            updateHeadView(momentListBean.getUserImage(),momentListBean.getCountRealInfo());
        }
        setData(isRefresh,momentListBean.getList());
        mNextPage++;
        Logger.e("onGetMomentListSuccess--"+mListType);
    }

    @Override
    public void onGetMomentListFailed(String errMsg) {
        mSwipeRefreshLayout.setRefreshing(false);
//        boolean isRefresh = mNextPage == 1;
//        if(isRefresh)  mAdapter.setEnableLoadMore(true);
        Logger.e("onGetMomentListFailed:"+errMsg);
    }

    @Override
    public void onLikeOrUnlikeSuccess(String result,int position) {
        Logger.e("onLikeOrUnlikeSuccess: "+result);
        int originalNum = mAdapter.getData().get(position).getLikeNum();
        if(LIKE_SUCCESS.equals(result)){
            mAdapter.getData().get(position).setNumber(MomentView.STATUS_LIKED);
            mAdapter.getData().get(position).setLikeNum(originalNum+1);
        }else if(UNLIKE_SUCCESS.equals(result)){
            mAdapter.getData().get(position).setNumber(MomentView.STATUS_UNLIKED);
            mAdapter.getData().get(position).setLikeNum(originalNum-1);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onLikeOrUnlikeFailed(String errMsg) {
        Logger.e("onLikeOrUnlikeFailed: "+errMsg);
    }

    @Override
    public void onReportSuccess() {
        Toast.makeText(getActivity(),getString(R.string.thank_you_for_reporting),Toast.LENGTH_SHORT).show();
    }


    @Override
    public void onDeleteSuccess(int position) {
        Logger.e("onDeleteSuccess"+position);
        mAdapter.getData().remove(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDeleteFailed(String errMsg) {
        Logger.e("onDeleteFailed:"+errMsg);
    }


    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
        if(view.getId() == R.id.more){
            Logger.e("onItemChildClick------------more more more ");
            final Moment moment = mAdapter.getItem(position);
            handleClickMore(position, moment);
        }else if(view.getId() == R.id.like_container){
            Logger.e("onItemChildClick------------like like like ");
            mPresenter.likeOrUnLike(mMineId,mAdapter.getData().get(position).getId(),position);
        }
    }

    private void handleClickMore(final int position, final Moment moment) {
        String action;
        if(UserPreferences.getInstance().getInt(UserPreferences.USER_ID) == moment.getUserId()){
            action = MomentActionDialog.ACTION_DELETE;
        }else {
            action = MomentActionDialog.ACTION_REPORT;
        }
        MomentActionDialog momentActionDialog = new MomentActionDialog(getActivity(),action);
        momentActionDialog.setOnActionClickListener(new MomentActionDialog.OnActionClickListener() {
            @Override
            public void onActionClicked(String action) {
                Logger.e("onActionClicked----"+action);
                if(MomentActionDialog.ACTION_DELETE.equals(action)){
                    mPresenter.deleteMoment(moment.getUserId(),moment.getId(),position);
                }else {
                    ReportSelectDialog reportSelectDialog = new ReportSelectDialog(getActivity());
                    reportSelectDialog.setOnReportSelectListener(new ReportSelectDialog.OnReportSelectListener() {
                        @Override
                        public void onSelected(String content) {
                            mPresenter.report(mMineId,moment.getId(),0,content);
                        }
                    });
                    reportSelectDialog.show();
                }
            }
        });
        momentActionDialog.show();
    }


    @Override
    public void onResume() {
        super.onResume();
        if(TYPE_LATEST.equals(mListType)){EventBus.getDefault().register(this);}
        Logger.e("MomentListFragment--onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        if(TYPE_LATEST.equals(mListType)) EventBus.getDefault().unregister(this);
    }

    @Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
    public void onDeleteMoment(MomentEvent event) {
        //由于跳转详情时onPause被执行取消了注册，所以要想收到消息需要使用sticky消息，当然也可以把注册和取消放在onCreate和onDestroy里面就无需sticky消息
        Logger.e("onDeleteMoment--"+event.getDeletePosition()+"--"+mListType);
        handleDelete(event.getDeletePosition());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {//貌似受嵌套或者ViewPager影响不回调啊  但BaseFragment里的依旧回调。。
        Logger.e("onHiddenChanged---------------？？？？？");
//        if(!hidden){
//            Logger.e("跑圈又可见啦");
//            refresh();
//        }else {
//            Logger.e("跑圈不可见啦");
//        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == MessageListActivity.REQUEST_MESSAGE_LIST){
                Logger.e("消息已读，删除head view");
                removeHeadView();
            }
        }
    }


    public void handleDelete(int position){
        if(position >=0 && position< mAdapter.getData().size()){
            if(mAdapter != null) {
                mAdapter.getData().remove(position);
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}
